package com.common.util;

import com.common.global.BussinessBaseEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
public class BussinessBaseEnumUtil {

    public static <T extends BussinessBaseEnum> T getByCode(Integer code, Class<T> enumClass) {
        Map<Integer, T> collect = Arrays.stream(enumClass.getEnumConstants()).collect(Collectors.toMap(T::getCode, Function.identity()));
        return collect.get(code);
    }

    public static <T extends BussinessBaseEnum> T getByText(String text, Class<T> enumClass) {
        Map<String, T> collect = Arrays.stream(enumClass.getEnumConstants()).collect(Collectors.toMap(T::getDesc, Function.identity()));
        return collect.get(text);
    }

    public static <T extends BussinessBaseEnum>  String codeToText(Integer code, Class<T> enumClass){
        T t = getByCode(code, enumClass);
        return Optional.ofNullable(t).map(BussinessBaseEnum::getDesc).orElse(null);
    }

    public static <T extends BussinessBaseEnum>  Integer textToCode(String text, Class<T> enumClass){
        T t = getByText(text, enumClass);
        return Optional.ofNullable(t).map(BussinessBaseEnum::getCode).orElse(null);
    }
}
